Skip to content

feat(rust): observe rust-model solutions natively - #5963

Merged
BradyPlanden merged 12 commits into
mainfrom
stack/08-native-observation
Dec 4, 2026
Merged

BradyPlanden merged 12 commits into
mainfrom
stack/08-native-observation

Conversation

@BradyPlanden

@BradyPlanden BradyPlanden commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Description

Reads variables, and their sensitivities, from a rust-model IDAKLUSolver solution in Rust.

  • set_up binds the CompiledModel to the model's ObserverCache (refactor: read solution variables through per-model observer caches #5786).
  • build_variable then evaluates each variable on a tape compiled into the model's retained graph: one Rust call per segment, cubic-Hermite between time points when the solution stores derivatives.
  • Sensitivities are computed by the chain rule in Rust, one JVP sweep per parameter per segment, with each sweep's directions handed over column-major for Rust to read in place.

Besides CompiledModel.graph, a getter it adds to the bindings with its stub, this PR is Python only; the other Rust methods it calls (n_states, ExprGraph.from_expr) are from #5962.

  • ObserverCache:
    • It gains bind_rust_model, native_leaf (a variable's tape, compiled once per model), native_set (several variables on one tape, sharing subexpressions) and post_sum_leaf.
    • Rebinding the model on a new set_up drops the native leaves.
    • A leaf is one segment's compiled form of one variable, as the module docstring of observation.py says.
  • NativeObserver: evaluates raw values (eval_trajectory), Hermite values (eval_trajectory_hermite) and sensitivities. Time integrals add their post-sum sensitivities through native_postfix_sensitivities. On an output_variables solve, a variable that is not an output reads its values and sensitivities from the placeholder states, as on the CasADi path.
  • Solution.update([...]):
    • It deduplicates the names and reads the eligible ones together. Each segment evaluates one SharedOutputs tape and sweeps its sensitivities once per parameter, and each variable reads its rows through a SharedOutputLeaf. A segment with no time points gives empty rows.
    • Values and sensitivities are bitwise equal to reading the names one by one.
    • It builds every listed variable before storing any, so if one fails (an unknown name, or a state-dependent variable on an output_variables solve) nothing is stored. Before, on CasADi and rust alike, the names before the failing one were rebuilt and kept. update("name") with one string is unchanged.
    • QuickPlot and Solution.get_data_dict build all their variables this way.
  • Time integrals: ProcessedVariableTimeIntegral.sum_over_time is public, and check_discrete_times is a method, for the native path.

When native reading applies:

  • A solution reads natively when every segment's model is a rust model set up by a solver that observes natively; in this PR that solver is IDAKLUSolver.
  • Other solutions read through CasADi, as do VectorField variables.
  • Time integrals and VectorField variables are read one by one, not on a shared tape.
  • Time-integral post-sum values are evaluated in Python.
  • Asking for sensitivities without calculate_sensitivities raises ValueError, as on main.
  • A variable that reads a time derivative raises ModelError as it compiles, the error CasADi's process raises (feat: IDAKLU termination events on time derivatives #6056).

On the CasADi path, values are unchanged. Solution.update deduplicates its names and stores all or nothing, and QuickPlot and get_data_dict build every variable up front.

Review on #5732

Type of change

New feature, under ## Features in CHANGELOG.md.

Key checklist

  • No style issues: pre-commit run
  • Unit tests pass (N), as do the integration tests (N)
  • Tests added: 80 Python test functions, with 3 existing tests parametrised over the format.
    • Native against CasADi reading, each from its own rust solve:
      • direct variables at rtol 1e-9;
      • time integrals, explicit integrals, discrete sums and experiments at 1e-7 to 1e-8;
      • dense t_interp;
      • 2D DFN and 3D MPM layouts at 1e-4.
    • Sensitivities: from a rust solve against a CasADi solve (rtol 1e-5).
    • Through IDAKLU:
      • off-grid reads, 1D and 2D variables, events, experiments and Hermite off;
      • sensitivities, including time integrals, and other variables' sensitivities on an output_variables solve;
      • first and last states, and a reduced solution;
      • no CasADi observe function compiled.
    • Batching: batched reads bitwise equal to per-name reads, over an empty segment, and from 8 threads at once; update storing nothing when one name fails.
    • Caching and fallback:
      • reuse across solves, rebinding and model copies;
      • joined solutions of two rust models;
      • a CasADi segment falling back to CasADi;
      • pickling.
Rust execution engine stack: proposal #5667, showcase #5732

Each PR builds on the one above it.

# PR Adds
0 #5954 Function.create_copy keeps the function's class
0b #5955 CasADi's RegPower and uniform-grid interpolant lookups match evaluate
1 #5956 pybamm-core: expression graph, typed IR, interpreters, forward-mode AD
2 #5957 pybamm-core: CompiledModel, coloured Jacobians, the C ABI
3 #5958 pybamm.rust bindings, built into the pybamm wheel
4 #5959 Symbol.to_rust
5 #5960 convert_to_format = "rust" for ScipySolver, AlgebraicSolver and EIS
6 #5961 pybammsolvers: IDAKLU over the C ABI
7 #5962 IDAKLUSolver on rust models
8 #5963 variables and sensitivities read in Rust ← this PR
9 #5964 pybamm-core: diffsol DAE solver
10 #5965 pybamm.DiffsolSolver
10a #6134 Interpolant over input parameters and expressions
10b #6138 pybamm.rust's own errors, array-likes, threads and Ctrl-C
10c #6135 pybamm.rust.inspection; every tape derived in one place
11 #5966 "rust" as the default convert_to_format

@codecov

codecov Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.32432% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 98.42%. Comparing base (6125a5b) to head (a42797f).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...es/pybamm/src/pybamm/solvers/processed_variable.py 80.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5963      +/-   ##
==========================================
+ Coverage   98.40%   98.42%   +0.02%     
==========================================
  Files         363      363              
  Lines       38745    39034     +289     
==========================================
+ Hits        38127    38421     +294     
+ Misses        618      613       -5     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@BradyPlanden
BradyPlanden force-pushed the stack/08-native-observation branch from 73c029c to 879f508 Compare October 28, 2026 09:55
@BradyPlanden
BradyPlanden force-pushed the stack/08-native-observation branch 2 times, most recently from 26c1029 to 63e4b86 Compare October 28, 2026 14:11
@BradyPlanden
BradyPlanden force-pushed the stack/08-native-observation branch 2 times, most recently from b77ac50 to 52b69b1 Compare October 29, 2026 08:01
@BradyPlanden
BradyPlanden marked this pull request as ready for review October 29, 2026 08:56
@BradyPlanden
BradyPlanden requested a review from a team as a code owner October 29, 2026 08:56
@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

ProjectPyBaMM
Branchstack/08-native-observation
Testbedbare-metal

⚠️ WARNING: Truncated view!

The full continuous benchmarking report exceeds the maximum length allowed on this platform.

🐰 View full continuous benchmarking report in Bencher

🔗 Link this project to GitHub

@BradyPlanden
BradyPlanden force-pushed the stack/08-native-observation branch from 52b69b1 to b55c69e Compare October 29, 2026 17:26
@BradyPlanden
BradyPlanden force-pushed the stack/08-native-observation branch from b55c69e to b6a75a5 Compare November 17, 2026 11:24
@BradyPlanden
BradyPlanden removed this pull request from stack #6136 November 30, 2026 11:52
@BradyPlanden
BradyPlanden changed the base branch from stack/07a-rust-ffi-layout to stack/07-idaklu-rust-mode November 30, 2026 11:54
@BradyPlanden
BradyPlanden added this pull request to stack #6139 November 30, 2026 11:54
@BradyPlanden
BradyPlanden force-pushed the stack/08-native-observation branch 2 times, most recently from 5699aaa to 0fc2584 Compare December 2, 2026 09:22
Base automatically changed from stack/07-idaklu-rust-mode to main December 2, 2026 22:32
A second reader in build_variable: a model bound with
ObserverCache.bind_rust_model reads each segment through native tapes kept
on its ObserverCache, with shared-tape variable sets and native sensitivities.
#6056 makes `x.diff(pybamm.t)` work through functions and observables, and
pins that observing one raises `ModelError("Must provide a 'y_dot'...")`:
observation gives a leaf no state derivatives. A native leaf compiled the
derivative regardless and failed only when read, with another message.

The native leaf and the native set now refuse a tape reading `y_dot` as they
compile, with the error `process` raises, so `Solution.observe` and
`Solution.update` fail the same way for either format.
`_sweep_sensitivities` built each parameter's direction as a C-order
`(n_states, n_t)` transpose of `dy_dp`, a strided copy that Rust then
gathered again into the column-major layout it reads. Gathering the column
first and reshaping gives an F-contiguous array, which Rust borrows.

Reading the sensitivities of a Rust DFN over 10,000 points, with three
parameters, drops from 242 ms to 15 ms for "Voltage [V]", and from 1.58 s
to 87 ms for six variables. At the 138 points the solver steps to, it drops
from 0.56 ms to 0.19 ms.
Reading Rust solutions natively is how IDAKLUSolver serves Rust models,
which no release reaches yet, so it takes no entry. What every backend
sees is `Solution.update([...])` now storing a list all or nothing, so
the entry records that.
Native observation compiled its leaves on the graph of the
CompiledModel a solver had bound to the model's ObserverCache, each
leaf lowering afresh. A model no solver bound, as ScipySolver left
every model, or a hand-built Solution read through CasADi, as did a
VectorField. The _observes_via_compiled_model flag chose which solvers
bound.

Every Rust model's variables, VectorField components among them, now
compile on its RustModelLowering, sharing its memo of lowered symbols,
and a leaf reads as many states as its segment stores. ObserverCache
keeps only CasADi leaves, and the flag goes. Setting the model up again
keeps its leaves; a copy compiles its own. Reading five variables of a
ScipySolver SPM solution takes 6 ms rather than 10 ms.
Native leaves were cached on the model's lowering by variable name, and
the lowering now outlives a set-up, so a variable given a new
expression went on reading the old one. A Solution whose inputs held
the model's names in another order replaced the model's lowering,
though leaves take their inputs by name, and each such read rebuilt the
graph and every leaf.

Leaves, shared tapes, time integrals and post-sum tapes are cached by
the expression they compile as well as the name. A segment reads
through the model's lowering whenever it has the segment's input names,
in whatever order. VariableObserver.with_leaves is abstract.
…l's graph

A Solution whose inputs were not the model's replaced the model's
lowering, dropping its CompiledModel and every compiled variable. It
now reads through a lowering of its own, and the model's is used only
for its own inputs, in any order, or made when the model has none.
A Solution whose inputs were not the model's made a new lowering for
every read and every segment, so each read recompiled every variable.
That lowering is now cached on the model's, by the set of input names.
- The single-set num_threads test compared one call with itself; only
  its pool check could fail, so it keeps that alone.
- The dense-grid test's read sat below its tolerance on a chord as well
  as a cubic; the flags carry the change. It now reads 4097 columns over
  one span, without a stop at every column.
- A first-interval read superseded by the analytic ones goes, and the
  stepped-current voltage check uses assert_allclose.
- ed2422fe2 (a failed set-up keeps the last good one) and 50bbe35eb
  (other inputs reuse one lowering per set of names) gain the tests
  that fail without them.
…all matching

Codecov found native observation's patch short of the project's
coverage. The Solution vector-field test now runs on both formats, so a
Rust model's components are read natively, through NativeObserver's
with_leaves and the lowering a hand-built Solution's model makes on
first read. A hand-built three-segment solution, its middle segment a
single knot, is read natively and through CasADi at query times in one
segment and in all three. A table test covers when a shared tape
reuses a held call.
@BradyPlanden
BradyPlanden force-pushed the stack/08-native-observation branch from 0fc2584 to 4cb7407 Compare December 3, 2026 11:03

@martinjrobins martinjrobins left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks great, thanks @BradyPlanden , just minor stuff below

A vector field compiled each component on its own and dropped the time
integral a component held, so a component read as its integrand in
place of its integral, through CasADi and natively alike. Reading such
a variable now raises NotImplementedError on either path.
NativeObserver, SharedOutputs and SharedOutputLeaf, the native
sensitivity helpers, and the native build functions now carry type
hints. Typing their bodies checks two invariants with casts: a vector
field's observer is read only per component, and a post-sum node always
has its compiled tape. A tape's inputs are a mapping or the packed
vector, as the bindings accept.

native_sensitivities, native_postfix_sensitivities and
chain_rule_sensitivities have no caller outside the module, so they
become private.

@martinjrobins martinjrobins left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

happy to merge 👍

@BradyPlanden
BradyPlanden added this pull request to the merge queue Dec 4, 2026
Merged via the queue into main with commit 702f05d Dec 4, 2026
62 checks passed
@BradyPlanden
BradyPlanden deleted the stack/08-native-observation branch December 4, 2026 12:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants